package com.xrkj.b2c.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * <B>系统名称：</B><BR>
 * <B>模块名称：</B><BR>
 * <B>中文类名：</B>系统异常统一处理<BR>
 * <B>概要说明：</B><BR>
 * @author 赵子靖
 * @since 2018年7月12日
 */
public class ExceptionHandler implements HandlerExceptionResolver {
    private Logger logger = Logger.getLogger(ExceptionHandler.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ex.printStackTrace();
        logger.error(ex.getMessage());
        String requestType = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType)) {
            //针对ajax访问请求异常处理
            Map<String, Object> ret = new HashMap<String, Object>();
            ret.put("code", -1);
            ret.put("success", false);
            if (ex instanceof BusinessException) {
                ret.put("msg", "业务异常"+ex.getMessage());
            } else {
                ret.put("msg", "系统访问异常"+ex.getMessage());
            }
            String jsonString = JSONObject.toJSONString(ret);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try {
                response.getWriter().write(jsonString);
                response.getWriter().flush();
                response.getWriter().close();
            } catch (Exception e) {
            }
            return null;
        } else {
            //页面请求访问异常类型
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("ex", ex);
            model.put("msg", ex.getMessage());
            // 根据不同错误转向不同页面  
            if (ex instanceof BusinessException) {
                //业务异常
                return new ModelAndView("WEB-INF/error/business-error", model);
            } else {
                //默认异常
                return new ModelAndView("WEB-INF/error/500", model);
            }
        }
    }

}
